package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TBill;
import com.ruoyi.system.service.ITBillService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 账单Controller
 *
 * @author ruoyi
 * @date 2025-06-22
 */
@RestController
@RequestMapping("/system/bill")
public class TBillController extends BaseController {
    @Autowired
    private ITBillService tBillService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询账单列表
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/list")
    public TableDataInfo list(TBill tBill) {
        startPage();
        List<TBill> list = tBillService.selectTBillList(tBill);
        return getDataTable(list);
    }

    /**
     * 小程序用户查询账单列表
     */
//    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/getBillByUserId")
    public AjaxResult getBillByUserId() {
        TBill bill = new TBill();
        bill.setUserId(SecurityUtils.getUserId());
        List<TBill> list = tBillService.selectTBillList(bill);
        return AjaxResult.success(list);
    }

    /**
     * 导出账单列表
     */
    @PreAuthorize("@ss.hasPermi('system:bill:export')")
    @Log(title = "账单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TBill tBill) {
        List<TBill> list = tBillService.selectTBillList(tBill);
        ExcelUtil<TBill> util = new ExcelUtil<TBill>(TBill.class);
        util.exportExcel(response, list, "账单数据");
    }

    /**
     * 获取账单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:bill:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tBillService.selectTBillById(id));
    }

    /**
     * 新增账单
     */
    @PreAuthorize("@ss.hasPermi('system:bill:add')")
    @Log(title = "账单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TBill tBill) {
        return toAjax(tBillService.insertTBill(tBill));
    }

    /**
     * 修改账单
     */
    @PreAuthorize("@ss.hasPermi('system:bill:edit')")
    @Log(title = "账单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TBill tBill) {
        return toAjax(tBillService.updateTBill(tBill));
    }

    /**
     * 删除账单
     */
    @PreAuthorize("@ss.hasPermi('system:bill:remove')")
    @Log(title = "账单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tBillService.deleteTBillByIds(ids));
    }

    /**
     * 管理员给用户充值账单
     */
    @PreAuthorize("@ss.hasPermi('system:bill:addBill')")
    @Log(title = "充值账单", businessType = BusinessType.INSERT)
    @PostMapping("/addBalanceBill")
    @Transactional(rollbackFor = Exception.class)//事务（代码报错，回滚之前执行的sql）
    public AjaxResult addBill(@RequestBody TBill tBill) {
        //  修改用户余额
        Long userId = tBill.getUserId();
        BigDecimal amount = tBill.getAmount();
        userService.updatieUserBalance(userId,amount);
        // 加一个充值账单记录
        tBill.setUserId(userId);
        tBill.setPayTime(new Date());
        tBill.setBillType(2L);
        tBill.setDescription("充值钱包");
        tBillService.insertTBill(tBill);
        // 成功
        return AjaxResult.success();
    }

    /**
     * wx用户充值账单
     */
    @Log(title = "充值账单", businessType = BusinessType.INSERT)
    @PostMapping("/addBillByUserId")
    @Transactional(rollbackFor = Exception.class)//事务（代码报错，回滚之前执行的sql）
    public AjaxResult addBillByUserId(@RequestBody TBill tBill) {

        // 加一个充值账单记录
        Long userId = SecurityUtils.getUserId();
        tBill.setUserId(userId);
        tBill.setBillType(1l);
        tBill.setPayTime(new Date());
        tBill.setDescription("充值钱包");
        tBillService.insertTBill(tBill);

        //  修改用户余额
        BigDecimal amount = tBill.getAmount();
        userService.updatieUserBalance(userId,amount);

        // 成功
        return AjaxResult.success();
    }



    /**
     * wx用户提现账单
     */
    @Log(title = "充值账单", businessType = BusinessType.INSERT)
    @PostMapping("/subtractBillByUserId")
    @Transactional(rollbackFor = Exception.class)//事务（代码报错，回滚之前执行的sql）
    public AjaxResult subtractBillByUserId(@RequestBody TBill tBill) {
        Long userId = SecurityUtils.getUserId();
        //  修改用户余额
        BigDecimal amount = tBill.getAmount().multiply(new BigDecimal(-1));
        userService.updatieUserBalance(userId,amount);
        // 加一个充值账单记录
        tBill.setUserId(userId);
        tBill.setBillType(2l);  //支出
        tBill.setPayTime(new Date());
        tBill.setDescription("钱包扣款提现");
        tBill.setAmount(amount); // 金额
        tBillService.insertTBill(tBill);
        // 成功
        return AjaxResult.success();
    }

}
